<?
	$grp = $this->grp;
?>
	
	function flagChange(){
		$('changesbutton').disabled = false;
		window.onbeforeunload = function(e){
		  var s = 'You have unsaved changes.';
		  if (e) e.returnValue = s;
		  return s;
		}
	}
	
	function unflagChange(){
		window.onbeforeunload = function(){}
	}

	var Group = {
		load:function(o){
			for(var k in o) this[k] = o[k];
		},
		save:function(){
			var args = {id:Group.id, members:Users.get()};
			var name = $('grpname').value.trim();
			if(!name || (name.length < 4)) return alert("The name cannot be less than 4 characters");
			if(name != Group.nam) args.name = name;
			ajaxExec('saveGroup', args);
			unflagChange();
		}
	};

	var Users = {
		uids:{},
		load:function(o, u){
			for(var k in o) Users.uids[k] = o[k];
			Users.draw();
		},
		add:function(id, usr){
			Users.uids[id] = usr;
			Users.draw();
			flagChange();
		},
		remove:function(id){
			var gs = Users.uids;
			Users.uids = {};
			for(var k in gs) if(k != id) Users.uids[k] = gs[k];
			Users.draw();
			flagChange();
		},
		draw:function(){
			$('groupmembers').innerHTML = '';
			for(var k in Users.uids){
				$('groupmembers').innerHTML += '<br />' + Users.uids[k].name
				+ ' <a style="font-size:0.8em" href="javascript:Users.remove(\'' + k + '\')">remove</a><br />';
			}
		},
		get:function(){
			var u = [];
			for(var k in Users.uids) u.push(k);
			return u.join(',');
		},
		browse:function(){
			Browser.goto('../users', {title:'Add user to group ' + Group.nam, xargs:{filter:'u:500,<?=$grp->primary?>'}});
			AppsB.clickHandler = function(){
				Users.add(this.id, this);
				Browser.hide();
			}	
		}
	};

	window.onload = function(){
		Chrome.load({
			Selection:0
		});
		Users.load(<?=json_encode(new obj(get_users($grp->members(), false)))?>);
		Group.load(<?=json_encode($grp->data())?>);
	};